<?php

namespace app\common\model;

use app\admin\model\Detail;
use app\admin\model\Luck;
use app\admin\model\Orderdetail;
use think\Db;
use think\Model;
use app\admin\model\Tuiconfig;
use app\admin\model\Otherconfig;

/**
 * 会员模型
 * @method static mixed getByUsername($str) 通过用户名查询用户
 * @method static mixed getByNickname($str) 通过昵称查询用户
 * @method static mixed getByMobile($str) 通过手机查询用户
 * @method static mixed getByEmail($str) 通过邮箱查询用户
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
    ];

    /**
     * 获取个人URL
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }

    /**
     * 获取头像
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }
    /**
     * 
     * 积分和水滴获取 
     * 二级分销
     * @param mixed $userId
     * @param mixed $money
     * @param mixed $type
     * @return bool
     */
    public static function getScoreAndWater($userId,$money,$type = 0)
    {
        $config = Tuiconfig::select();//推广的配置
        $tmpConfig = [];
        foreach($config as $value) {
            if($value['type'] == $type) {
                $tmpConfig = $value;
                break;
            }
        }
        if($type == 0) {
            $user = User::find($userId);
            //计算我可以得到多少积分和水滴 
            // $score = $money *  $tmpConfig['score'];//积分
            // $water = $money * $tmpConfig['water'];//水滴
            $score = 10;//积分
            $water = 10;//水滴
            //记录起来
            $user->score = $user->score +  $score;
            $user->num = $user->num +  $water;
            $user->save();
            ScoreLog::insert(['pid' => $user['pid'],'createtime' => time(),'user_id' => $userId,'before' => $user['score'],'score' =>  $score,'after' =>  $user->score ,'memo' => '自购返积分','status' => 0,'type' =>1]);
            ScoreLog::insert(['pid' => $user['pid'],'createtime' => time(),'user_id' => $userId,'before' => $user['num'],'score' =>  $water,'after' =>  $user->num ,'memo' => '自购返水滴','status' => 1,'type' => 0]);
            if($user['pid']) {#如果有上级
                self::getScoreAndWater($user['pid'],$money,1);
            }
        }
        if($type == 1) {//上级只能获取推广收益
            $user = User::find($userId);
            $water = $money * $tmpConfig['water'];//水滴
            $water = 10;//水滴
            $user->num = $user->num +  $water;
            $user->save();
            ScoreLog::insert(['pid' => $user['pid'],'createtime' => time(),'user_id' => $userId,'before' => $user['num'],'score' =>  $water,'after' =>  $user->num ,'memo' => '推广收益','status' => 0,'type' => 2]);
            if($user['pid']) {
                self::getScoreAndWater($user['pid'],$money,2);
            }
        }
        if($type == 2) {//上上级只能获取推广收益
            $user = User::find($userId);
            $water = $money * $tmpConfig['water'];//水滴
            $water = 10;//水滴
            $user->num = $user->num +  $water;
            $user->save();
            ScoreLog::insert(['pid' => $user['pid'],'createtime' => time(),'user_id' => $userId,'before' => $user['num'],'score' =>  $water,'after' =>  $user->num ,'memo' => '推广收益','status' => 0,'type' => 2]);
            if($user['pid']) {
                self::getScoreAndWater($user['pid'],$money,2);
            }
        }
        return true;
    }
    //我的押金桶
    public static function addBucket($userId,$num = 1)
    {
        $otherConfig = Otherconfig::find(1);
        $images = Attachment::where('category','category3')->find(); 
        return Db::name('bucket')->insert(['image' => $images['url'],'user_id' => $userId,'num' => $num,'money' => $otherConfig['bucket'] * $num,'create_time' => time()]);
    }
    /**
     * 
     * 从购物车中删除
     * @param mixed $detailIds
     * @return int
     */
    public static function dealCarList($detailIds,$userId)
    {
        if(is_string($detailIds)) {
            $ids = explode(',',$detailIds);
         }
         return Db::name('cart')->where(['user_id' => $userId])->where('detail_id', 'in', $ids)->delete();
    }
    
    public static function decNum($orderId)
    {
        $orderDetail = Orderdetail::where('order_sn',$orderId)->select();
        foreach($orderDetail as $value) {
            Detail::where('id',$value['detail_id'])->dec('num',$value['num'])->update();
        }
        return true;
    }
    public static function dealTicket($ids,$userId)
    {
        if(empty($ids)) return false;
        $ticketIds = explode(',',$ids);//变成数组
        Db::name('user_ticket_record')->where('id','in',$ticketIds)->update(['stauts' =>2]);
        $list =  Db::name('user_ticket_record')->where('id','in',$ticketIds)->select();
        $tmpData = [];
        foreach($list as $value) {#把对应的ticket_id找出来
            array_push($tmpData,$value['ticket_id']);
        }
        $tmpData = array_unique($tmpData);//把票据都找出来
        foreach($tmpData as $value) {
            $hasRecord = Db::name('user_ticket_record')->where(['user_id' => $userId,'status' =>1,'ticket_id' => $value])->find();
            if(!$hasRecord ) {//如果没了
                Db::name('user_tikcet')->where('id',$value)->update(['status' => 2]);
            }
        }
        return true;
    }
   
}
